// 数据库操作
const mongoose = require('mongoose');
// 模型规则类
const {
    Schema
} = mongoose;

// 对象规则验证
const Joi = require('joi');
// 床模型规则，Bed集合用于标识每个房型中包含的床位类型及其对应的数量
const bedSchema = new Schema({
    // 所属床型ID
    type: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'BedType'
    },
    serial: {
        type: Number,
        required: true,
        default: 1,
        min: 1,
        max: 8
    },
    isUpper: {
        type: Boolean,
        required: true,
        default: false
    },
    direction: {
        type: Number,
        required: true,
        default: 0,
        min: 0,
        max: 3
    },
    children: [{
        type: Schema.ObjectId,
        ref: 'Bed'
    }],
    isDeleted: {
        type: Boolean,
        default: false
    }
}, {
    versionKey: false
});

const Bed = mongoose.model('Bed', bedSchema);

// 床格式校验
const validateBed = bed => {
    // 定义对象验证规则
    const schema = {
        type: Joi.string().required().regex(/^[0-9a-fA-F]{24}$/).error(new Error('床型不能为空或不符合id规则')),
        serial: Joi.number().required().min(1).max(8).error(new Error("床铺序号不能为空，取值范围为1~8")),
        isUpper: Joi.boolean().error(new Error('是否上铺字段数据格式不正确'))
    };
    // 验证
    return Joi.validate(bed, schema, {
        // 检测到所有错误
        abortEarly: false,
        // 允许对象包含被忽略的未知键
        allowUnknown: true
    });
}

// 导出模块成员
module.exports = {
    Bed,
    validateBed
}